#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@FileName  :utils.py 
@desc      : 邮箱验证
@Author    :Young
@IDE       :PyCharm
@Time      :2021/2/21 0021 9:44
'''
#一是产生token发送邮件，
#二是处理验证连接，采用base64进行加密，采用itsdangrous进行序列化

from itsdangerous import URLSafeTimedSerializer as utsr   #URLSafeTimedSerializer将其他类型转化为字符串
import base64
from django.conf import settings as django_settings

class Token:  #自定义模块
    def __init__(self, security_key):
        self.security_key = security_key
        self.salt = base64.encodebytes(security_key.encode('utf8'))

    def generate_validate_token(self, username): #生成token
         serializer = utsr(self.security_key)
         return serializer.dumps(username, self.salt)

    def confirm_validate_token(self, token, expiration=3600):#确认token，解密 expiration 过期的时间
        serializer = utsr(self.security_key)
        return serializer.loads(token, salt=self.salt,max_age=expiration)

    def remove_validate_token(self, token):
         serializer = utsr(self.security_key)
         print(serializer.loads(token, salt=self.salt))
         return serializer.loads(token, salt=self.salt)

token_confirm = Token(django_settings.SECRET_KEY) # 定义为全局变量